<template>
    <div class="address-container">
        <!-- 标题区域开始 -->
        <div class="title-wrap">
            <div class="left-wrap">
                <i class="iconfont icon-address"></i>
                <span>地址管理</span>
            </div>
            <el-button type="primary" size="default" @click="showAddDeliveryAddr">+添加地址</el-button>
        </div>
        <!-- 标题区域结束 -->

        <!-- 内容区域开始 -->
        <div class="content-wrap">
            <!-- 骨架屏区域开始 -->
            <el-skeleton animated :loading="isShowSkeleton" style="display: flex;flex-wrap: wrap;">
                <template #template>
                    <div class="address-item" v-for="(item, index) in 4" :key="index">
                        <div class="title">
                            <el-skeleton-item style="width: 80px;height: 25px;" />
                            <el-skeleton-item style="width: 60px;height: 25px;" />
                        </div>

                        <div class="content">
                            <div class="content-item">
                                <el-skeleton-item style="width: 80px;height: 25px;" />
                                <el-skeleton-item style="width: 100px;height: 25px;margin-left: 10px;" />
                            </div>

                            <div class="content-item">
                                <el-skeleton-item style="width: 100px;height: 25px;" />
                                <el-skeleton-item style="height: 25px;margin-left: 10px;" />
                            </div>
                        </div>

                        <div class="footer">
                            <el-skeleton-item style="width: 60px;height: 30px;" />
                                <el-skeleton-item style="width: 60px;height: 30px;margin-left: 10px;" />
                        </div>
                    </div>
                </template>
            </el-skeleton>
            <!-- 骨架屏区域结束 -->
            <div class="address-item" v-for="(item, index) in userAddrList" :key="index">
                <div class="title">
                    <span>{{item.name}}</span>
                    <span class="default-txt" v-if="item.is_default">默认</span>
                </div>

                <div class="content">
                    <div class="content-item">
                        <span class="name">手机号：</span>
                        <span class="txt">{{item.mobile}}</span>
                    </div>

                    <div class="content-item">
                        <span class="name">详细地址：</span>
                        <span class="txt">{{item.region}} {{ item.address }}</span>
                    </div>
                </div>


                <div class="footer">
                    <el-button type="default" size="default" @click="handlerEditDeliveryAddr(item)">编辑</el-button>
                    <el-button type="danger" size="default" @click="handlerDelete(item)">删除</el-button>
                </div>
            </div>

            <Empty style="margin: 0 auto;" v-if="userAddrList.length == 0"/>
        </div>
        <!-- 内容区域结束 -->

        <!-- 添加、编辑弹层开始 -->
        <el-drawer v-model="drawer" size="26%">
            <template #header>
                <div class="header-wrap">{{title}}</div>
            </template>

            <template #default>
                <div class="content-wrap">
                    <el-form :model="formData" :rules="rules" ref="formRef" style="width: 100%;">
                        <!-- 收货人 -->
                        <el-form-item label="收货人" :label-width="formLabelWidth" prop="name">
                            <el-input v-model="formData.name" autocomplete="off" maxlength="100"
                show-word-limit clearable placeholder="请输入收货人"/>
                        </el-form-item>

                        <!-- 手机号 -->
                        <el-form-item label="手机号" :label-width="formLabelWidth" prop="mobile">
                            <el-input v-model="formData.mobile" autocomplete="off" maxlength="11"
                show-word-limit clearable placeholder="请输入手机号"/>
                        </el-form-item>

                        <!-- 是否默认 -->
                        <el-form-item label="是否默认" :label-width="formLabelWidth">
                            <el-switch v-model="formData.is_default" active-text="是" active-value="1" inactive-text="否" inactive-value="0" />
                        </el-form-item>

                        <!-- 地区 -->
                        <el-form-item label="地区" :label-width="formLabelWidth" prop="region_ids">
                            <el-cascader ref="cascaderRef" :props="props" separator=" - " style="width: 100%;" v-model="formData.region_ids"></el-cascader>
                        </el-form-item>


                        <!-- 详细地址 -->
                        <el-form-item label="详细地址" :label-width="formLabelWidth" prop="address">
                            <el-input
                                v-model="formData.address"
                                :autosize="{ minRows: 2, maxRows: 4 }"
                                type="textarea"
                                placeholder="请输入详细地址"
                            />
                        </el-form-item>

                        
                    </el-form>
                </div>
            </template>

            <template #footer>
                <div>
                    <el-button @click="drawer = false">取消</el-button>
                    <el-button type="primary" @click="handlerConfirmAddress">确定</el-button>
                </div>
            </template>
        </el-drawer>
        <!-- 添加、编辑弹层结束 -->
    </div>
</template>

<script setup>
import { ref, reactive, inject, onMounted } from "vue"

import { reqAddUserDeliveryAddrAPI, reqDeleteUserDeliveryAddrAPI, reqEditUserDeliveryAddrAPI, reqUserDeliveryAddrListAPI } from '@/apis/userDeliveryAddr'
import { reqRegionListAPI } from '@/apis/region'

import { useUserStore } from "@/stores/modules/user"

import { ElNotification, ElMessageBox } from 'element-plus'



// ---------------- 定义全局变量开始 ----------------
// 定义用户存储
const userStore = useUserStore()

// 获取全局对象
const global = inject('global')

// 定义是否显示骨架
const isShowSkeleton = ref(false)

// 定义用户收货地址数据
const userAddrList = ref([])

// 提交数据
const formData = reactive({
	id: 0,
	name: '',
	mobile: '',
	province_id: 0,
	city_id: 0,
	district_id: 0,
	region: '',
	address: '',
	is_default: 0,
    region_ids: []
})

const formRef = ref()

// 定义手机号验证规则
const validateMobile = (rule, value, callback) => {
    let reg = /^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\d{8}$/
    if (!reg.test(value)) {
        callback('请输入正确格式的手机号!')
    } else {
        callback()
    }
}

// 验证规则
const rules = {
	name: [{ required: true, message: '收货人不能为空!', trigger: 'blur' }],
	mobile: [
        { required: true, message: '手机号不能为空!', trigger: 'blur'},
		{ validator: validateMobile, trigger: 'blur' }
	],
	region_ids: [
        { required: true, message: '请选择地区!', trigger: 'change'},
	],
	address: [{ required: true, message: '详细地址不能为空!' }]
}

// 标题
const title = ref('添加收货地址')

// 是否显示弹层
const drawer = ref(false)

// 表单标签宽度
const formLabelWidth = ref('80px')

// 地区变量
let props = reactive({})

// 定义父级ID
const pid = ref(0)

// 定义地区IDS
// const region_ids = ref([])

const cascaderRef = ref(null)
// ---------------- 定义全局变量结束 ----------------



onMounted(() => {
	getUserAddrList()
})



// -------------- 收货地址列表功能开始 --------------
// 获取用户收货地址
const getUserAddrList = async () => {
	// 显示骨架
    isShowSkeleton.value = true

	// 请求用户收货地址数据
	const result = await reqUserDeliveryAddrListAPI({status: 1})
  	userAddrList.value = result.data.user_delivery_addrs != null ? result.data.user_delivery_addrs : []

	// 隐藏骨架
    isShowSkeleton.value = false
}
// -------------- 收货地址列表功能结束 --------------



// -------------- 新增收货地址功能开始 --------------
const opt = ref('add')

// 重置参数
const resetForm = () => {
    formData.id = 0
	formData.name = ''
	formData.mobile = ''
	formData.is_default = 0
	formData.province_id = 0
	formData.city_id = 0
	formData.district_id = 0
	formData.region = ''
	formData.address = ''
    formData.region_ids = []

    pid.value = 0
    props = {}
}

// 显示新增收货地址
const showAddDeliveryAddr = async () => {
	opt.value = 'add'
	
	// 重置表单
    resetForm()

    props = {
        lazy: true,
        async lazyLoad (node, resolve) {
            const { level,value } = node;
            pid.value = level == 0 ? pid.value : value
            let result = await reqRegionListAPI({pid: pid.value, page_size: -1, sort_type: 'asc'})
            const nodes = result.data.regions.map((item) => ({
                value: item.id,
                label: item.name,
                leaf: level >= 2
            }))
            // 通过调用resolve将子节点数据返回，通知组件数据加载完成
            resolve(nodes)
        }
    }
	
	drawer.value = true
}
// -------------- 新增收货地址功能结束 --------------



// -------------- 编辑收货地址功能开始 --------------
const handlerEditDeliveryAddr = async (item) => {
	opt.value = 'edit'
    title.value = '编辑收货地址'

	// 重置表单
    resetForm()

    props = {
        lazy: true,
        async lazyLoad (node, resolve) {
            const { level,value } = node;
            pid.value = level == 0 ? pid.value : value
            let result = await reqRegionListAPI({pid: pid.value, page_size: -1, sort_type: 'asc'})
            const nodes = result.data.regions.map((item) => ({
                value: item.id,
                label: item.name,
                leaf: level >= 2
            }))
            // 通过调用resolve将子节点数据返回，通知组件数据加载完成
            resolve(nodes)
        }
    }
	
	// 赋值表单
	formData.id = item.id
	formData.name = item.name
	formData.mobile = item.mobile
	formData.is_default = item.is_default
	formData.province_id = item.province_id
	formData.city_id = item.city_id
	formData.district_id = item.district_id
	formData.region = item.region
	formData.address = item.address
    formData.region_ids = [item.province_id, item.city_id, item.district_id]
	
	drawer.value = true
}
// -------------- 编辑收货地址功能结束 --------------



// ---------------- 处理确认功能开始 ----------------
const handlerConfirmAddress = async () => {
    // 在你发请求之前,要对于整个表单进行校验
    // 调用这个方法进行全部表单相校验,如果校验全部通过，在执行后面的语法
    await formRef.value.validate();
    if (formData.region_ids.length != 3) {
        ElNotification.error('请选择地区')
        return false
    }

    formData.province_id = formData.region_ids[0]
    formData.city_id = formData.region_ids[1]
    formData.district_id = formData.region_ids[2]

    let checkedNodes = cascaderRef.value.getCheckedNodes(true)
    formData.region = checkedNodes[0].text.replace(/\s*/g, "")

    let result = null
    if (opt.value == 'add') {//新增
        result = await reqAddUserDeliveryAddrAPI(formData)
    } else { // 编辑
        result = await reqEditUserDeliveryAddrAPI(formData)
    }

    // 判断当前收货地址是否默认,如果默认则需要将其他地址修改为非默认
    if (formData.is_default == 1) {
        userAddrList.value.forEach((item) => {
            item.is_default = 0
        })
    }

    if (opt.value == 'add') {
        formData.id = result.data.id
        // 必须使用深拷贝，否则点击编辑的时候重新给formData赋值的时候也会修改新增的收货地址
        userAddrList.value.unshift(JSON.parse(JSON.stringify(formData)))
    } else {
        // 更新列表数据
        const deliveryAddr = userAddrList.value.find((item) => item.id == formData.id)
        for (const key in formData) {
            deliveryAddr[key] = formData[key]
        }
    }

    ElNotification({type: 'success', message: result.message})

    // 如果是默认地址，添加到 pinia 
    if (formData.is_default == 1) {
        userStore.setDeliveryAddr({
            id: formData.id,
            name: formData.name,
            mobile: formData.mobile,
            province_id: formData.province_id,
            city_id: formData.city_id,
            district_id: formData.district_id,
            region: formData.region,
            address: formData.address,
            is_default: formData.is_default
        })
    }
    
    drawer.value = false
}
// ---------------- 处理确认功能结束 ----------------



// ---------------- 处理删除功能开始 ----------------
const handlerDelete = (item) => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        await reqDeleteUserDeliveryAddrAPI({ids: item.id})
        // 从数据中删除
        const index = userAddrList.value.findIndex((v) => v.id == item.id)
        userAddrList.value.splice(index, 1)

        // 判断当前删除的地址是否为选中的地址，是则需要删除持久化的数据
        const deliveryAddr = userStore.deliveryAddr
        if (item.id == deliveryAddr.id) {
            userStore.clearDeliveryAddr()
        }

        ElNotification({type: 'success', message: '删除收货地址成功'})
    }).catch(() => {})
}
// ---------------- 处理删除功能结束 ----------------
</script>

<style scoped lang="scss">
.address-container {
    background-color: #fff;
    padding: 0 15px 15px 15px;

    // 标题区域
    .title-wrap {
        padding: 15px 0;
        font-size: 18px;
        border-bottom: 1px solid #f5f5f5;
        color: $main-color;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .left-wrap {
            display: flex;
            align-items: center;
            .iconfont {
                font-size: 24px;
                margin-right: 5px;
            }
        }
    }

    // 内容区域
    .content-wrap {
        display: flex;
        flex-wrap: wrap;
        .address-item {
            width: 48%;
            border: 1px solid #ccc;
            padding: 10px;
            margin: 10px 9px;
            border-radius: 5px;
            .title {
                font-size: 18px;
                padding: 15px 0;
                border-bottom: 1px solid #f5f5f5;
                display: flex;
                justify-content: space-between;
                color: #666;
                .default-txt {
                    font-size: 14px;
                    color: $main-color;
                }
            }

            .content {
                padding: 10px 0;
                color: #999;
                .content-item {
                    display: flex;
                    align-items: center;
                    padding: 6px 0;
                    .name {
                        width: 90px;
                        color: #666;
                        font-size: 17px;
                    }
                    .txt {
                        line-height: 24px;
                        flex: 1;
                    }
                }
            }
            .footer {
                display: flex;
                justify-content: flex-end;
                border-top: 1px solid #f5f5f5;
                padding-top: 10px;
            }
        }
    }

    ::v-deep(.el-drawer__header) {
        margin-bottom: 0;
        padding-bottom: 12px;
        border-bottom: 1px solid #f5f5f5;
    }

    .header-wrap {
        font-weight: bold;
        text-align: center;
    }
}
</style>